//
//  CollectTableViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/10.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "CollectTableViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <LYEmptyView/UIView+Empty.h>
#import "UIViewController+Empty.h"
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"
#import "CollectTableViewCell.h"
#import "DetailViewController.h"
#import "NetManager.h"
@interface CollectTableViewController ()
{
    int pageNumber;
    int rowNumber;
}
@property (nonatomic, strong) NSMutableArray *lists;
@end

@implementation CollectTableViewController

#pragma mark - lifeCycle
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    pageNumber = 1;
    rowNumber = 10;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadDataIsHeaderRefresh:YES];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadDataIsHeaderRefresh:NO];
    }];
    //设置空内容占位图
    self.tableView.ly_emptyView = [self emptyViewLoadDataBlock:^{
        [self loadDataIsHeaderRefresh:YES];
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadDataIsHeaderRefresh:YES];
    if (self.type == INTERACTIVETYPE_SCAN) {
        UIBarButtonItem *clearItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"clearAll"] style:UIBarButtonItemStylePlain target:self action:@selector(clearAllScanHistory)];
        clearItem.tintColor = [UIColor redColor];
        self.navigationItem.rightBarButtonItem = clearItem;
    }
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lists.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CollectTableViewCell *cell;
    NSDictionary *info = [self.lists safeObjectAtIndex:indexPath.row];
    if (self.type == INTERACTIVETYPE_SCAN) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"scanCell" forIndexPath:indexPath];
        cell.scanTimeLabel.text = [info safeObjectForKey:@"time"];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"collectCell" forIndexPath:indexPath];
         cell.moreLabel.text = [info safeObjectForKey:@"imtro"];
    }
    // Configure the cell...
    [cell.foodImgView sd_setImageWithURL:[NSURL URLWithString:[info safeObjectForKey:@"albums"]] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        NSLog(@"收藏/浏览 图片尺寸：%@", NSStringFromCGSize(image.size));
    }];
    cell.titleLabel.text = [info safeObjectForKey:@"title"];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detailVC = [DetailViewController detailVCFromStroyBoard];
    detailVC.view.backgroundColor = [UIColor whiteColor];
    detailVC.title = [self.lists[indexPath.row] safeObjectForKey:@"title"];
    NSInteger foodID = [[self.lists[indexPath.row] safeObjectForKey:@"c_id"] integerValue];
    detailVC.foodID = foodID;
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/details" params:@{@"id":[NSString stringWithFormat:@"%ld",(long)foodID], @"uid":[User userID]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *foodInfo = [[[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"] safeObjectAtIndex:0];
        detailVC.foodInfo = foodInfo;
        [self.navigationController pushViewController:detailVC animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - public
+ (instancetype)collectVCFromStoryBoard {
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CollectVC"];
}
#pragma mark - private
- (void)loadDataIsHeaderRefresh:(BOOL)isHeaderRefresh {
    if (isHeaderRefresh) {
        pageNumber = 1;
    }else {
        pageNumber++;
    }
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/b_list" params:@{@"uid":[User userID], @"type":@(self.type), @"page":@(pageNumber)} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"show_data"] isKindOfClass:[NSArray class]] && [[responseObject safeObjectForKey:@"show_data"] count] != 0) {
            if (isHeaderRefresh) {
                self.lists = [NSMutableArray arrayWithArray:[responseObject safeObjectForKey:@"show_data"]];
                [self.tableView.mj_header endRefreshing];
            }else {
                [self.lists addObjectsFromArray:[responseObject safeObjectForKey:@"show_data"]];
                [self.tableView.mj_footer endRefreshing];
            }
        } else {
            if (isHeaderRefresh) {
                [self.tableView.mj_header endRefreshing];
            }else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (isHeaderRefresh) {
            [self.tableView.mj_header endRefreshing];
        }else {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}
- (void)clearAllScanHistory {
    if (self.lists.count == 0) {
        return;
    }
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/emptying" params:@{@"uid":[User userID], @"type":@(self.type)} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"code"] integerValue] == 1) {
            self.lists = nil;
            [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - setter
- (void)setType:(INTERACTIVETYPE)type {
    _type = type;
}
@end
